package ad.manager.testfileprovider;

import androidx.appcompat.app.AppCompatActivity;

import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    EditText editText;
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView=findViewById(R.id.tv_main);
        editText=findViewById(R.id.edit_uri);
        button=findViewById(R.id.btn_get);
        String uri = getIntent().getStringExtra("uri");
        if (uri==null){
            textView.setText("uri为空");
        }else {
            editText.setText(uri);
        }
        button.setOnClickListener(v -> {
            String s = readText(Uri.parse(editText.getText().toString()));

            if (s!=null){
                textView.setText(s);
            }else {
                textView.setText("没有数据");
            }
        });
        if (uri!=null) {
            String s = readText(Uri.parse(uri));
            if (s != null) {
                textView.setText(s);
            } else {
                textView.setText("没有数据");
            }
        }
    }


    private String readText(Uri uri) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream inputStream = null;


        try {
            inputStream =
                    getContentResolver().openInputStream(uri);

            byte[] buffer = new byte[1024];

            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            byte[] b = baos.toByteArray();

            String s = null;
            if (b != null) {
                s = new String(b);
            }
            return s;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}